package com.youme.api

import com.salton123.app.BaseApplication
import com.youme.RouterManager
import com.youme.YouMeConfig
import com.youme.util.PreferencesUtils
import okhttp3.Interceptor
import okhttp3.Response

/**
 * Time:3/19/21 10:35 PM
 * Author:
 * Description:
 */
object TokenInterceptor : Interceptor {
    private val TAG = "TokenInterceptor"
    private var mToken: String = PreferencesUtils.getString(YouMeConfig.KEY.PREF_TOKEN, "")
    override fun intercept(chain: Interceptor.Chain): Response {
        val path = chain.request().url.toUrl().file

        val isIgnoredHeader = hashSetOf(
            "/rest/user/formLogin",
            "/rest/user/mobileLogin",
            "/rest/user/code",
            "/rest/user/reg"
        ).contains(path)
        val request = chain.request().newBuilder()
            .apply {
                if (!isIgnoredHeader) {
                    header("Authorization", mToken)
                }
            }.build()
        val resp = chain.proceed(request)
        if (resp.code == 401) {    //登录无效，说明token过期
            RouterManager.smsLogin(BaseApplication.sInstance)
        }
        return resp
    }

    fun updateToken(token: String) {
        mToken = token
        PreferencesUtils.putString(YouMeConfig.KEY.PREF_TOKEN, token)
    }
}